package com.yanqu.road.server.manger.config;

import com.yanqu.road.dao.impl.config.MusicRoomConfigDaoImpl;
import com.yanqu.road.entity.config.badge.BadgeConfig;
import com.yanqu.road.entity.config.beauty.BeautyInfo;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.config.musicroom.MusicRoomBeautyInitAttrConfig;
import com.yanqu.road.entity.config.musicroom.MusicRoomBuildBaseConfig;
import com.yanqu.road.entity.config.musicroom.MusicRoomFurnitureConfig;
import com.yanqu.road.entity.config.musicroom.MusicRoomMissionConfig;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.musicroom.*;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.manger.ConfigMgr;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

public class MusicRoomConfigMgr extends TempMgr {
    private static Map<Integer, MusicRoomFurnitureConfig> furnitureLevelConfigMap = new HashMap<>();
    private static Map<Short, Map<Integer, MusicRoomBeautyInitAttrConfig>> beautyInitAttrConfigMap = new HashMap<>();
    private static List<Integer> beautyAttrLvUpMultiList = new ArrayList<>();
    private static List<Integer> beautyAttrQualityMultiList = new ArrayList<>();
    private static List<List<Integer>> scheduleList = new ArrayList<>();
    private static List<Integer> lifeScheduleList = new ArrayList<>();
    private static Map<Integer, MusicRoomBuildBaseConfig> buildBaseConfigMap = new HashMap<>();
    private static Map<Integer, MusicRoomMissionConfig> missionConfigMap = new HashMap<>();
    /**
     * 建筑解锁消耗
     */
    private static Map<Integer, Property> buildingUnlockCostMap = new HashMap<>();
    private static int firstStageId = 0;
    /**
     * 徽章等级对应的建筑id集合
     */
    private static Map<Integer, Set<Integer>> badgeUnlockBuildingsMap = new HashMap<>();
    /**
     * 产出经验书的家具种类id集合
     */
    private static Set<Integer> expBookFurnitureKindSet = new HashSet<>();
    /**
     * 产出应援物的家具种类id集合
     */
    private static Set<Integer> supportsFurnitureKindSet = new HashSet<>();
    /**
     * 初始为1级的家具
     */
    private static Set<Integer> initFurnitureSet = new HashSet<>();
    /**
     * 评价抽取列表
     */
    private static List<Integer> appraiseNumList = new ArrayList<>();
    /**
     * 好评加成
     */
    private static List<List<Integer>> appraiseAdditionList = new ArrayList<>();

    private static int nowTimeNumber = -1;
    /**
     * 下一个路线时间点的时间戳 毫秒
     */
    private static long nextTimeNumberTime = 0;
    /**
     * 下一个奖励时间点的时间戳 毫秒
     */
    private static long nextRewardTime = 0;

    private static RandomHelper randomHelper = new RandomHelper();

    @Override
    public boolean init() throws Exception {
        addManagerReloadListener();
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        reloadMusicRoomConfig();
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    public static void reloadMusicRoomConfig() {
        Map<Integer, MusicRoomFurnitureConfig> tempFurnitureConfigMap = new MusicRoomConfigDaoImpl().getMusicRoomFurnitureConfigMap();
        Map<Integer, MusicRoomMissionConfig> tempMissionConfigMap = new MusicRoomConfigDaoImpl().getMusicRoomMissionConfigMap();

        Map<Short, Map<Integer, MusicRoomBeautyInitAttrConfig>> tempBeautyInitAttrConfigMap = new HashMap<>();
        {
            Map<Integer, MusicRoomBeautyInitAttrConfig> tempMap = parseBeautyInitAttrConfig(eOccupationType.Scholar.getValue(), GameConfig.MUSIC_ROOM_BEAUTY_INIT_ATTRIBUTE_1);
            tempBeautyInitAttrConfigMap.put(eOccupationType.Scholar.getValue(), tempMap);
        }
        {
            Map<Integer, MusicRoomBeautyInitAttrConfig> tempMap = parseBeautyInitAttrConfig(eOccupationType.Farmer.getValue(), GameConfig.MUSIC_ROOM_BEAUTY_INIT_ATTRIBUTE_2);
            tempBeautyInitAttrConfigMap.put(eOccupationType.Farmer.getValue(), tempMap);
        }
        {
            Map<Integer, MusicRoomBeautyInitAttrConfig> tempMap = parseBeautyInitAttrConfig(eOccupationType.Craftsman.getValue(), GameConfig.MUSIC_ROOM_BEAUTY_INIT_ATTRIBUTE_3);
            tempBeautyInitAttrConfigMap.put(eOccupationType.Craftsman.getValue(), tempMap);
        }
        {
            Map<Integer, MusicRoomBeautyInitAttrConfig> tempMap = parseBeautyInitAttrConfig(eOccupationType.Businessman.getValue(), GameConfig.MUSIC_ROOM_BEAUTY_INIT_ATTRIBUTE_4);
            tempBeautyInitAttrConfigMap.put(eOccupationType.Businessman.getValue(), tempMap);
        }
        {
            Map<Integer, MusicRoomBeautyInitAttrConfig> tempMap = parseBeautyInitAttrConfig(eOccupationType.Knight.getValue(), GameConfig.MUSIC_ROOM_BEAUTY_INIT_ATTRIBUTE_5);
            tempBeautyInitAttrConfigMap.put(eOccupationType.Knight.getValue(), tempMap);
        }

        List<Integer> tempBeautyAttrUpMultiList = StringUtils.stringToIntegerList(GameConfig.MUSIC_ROOM_BEAUTY_ATTRIBUTE_UPGRADE_MULTIPLE, "\\|");
        List<Integer> tempBeautyAttrQualityMultiList = StringUtils.stringToIntegerList(GameConfig.MUSIC_ROOM_BEAUTY_ATTRIBUTE_QUALITY_MULTIPLE, "\\|");

        List<List<Integer>> tempScheduleList = new ArrayList<>();
        for (String s : GameConfig.MUSIC_ROOM_SCHEDULE.split("\\|")) {
            List<Integer> temp = StringUtils.stringToIntegerList(s, ";");
            tempScheduleList.add(temp);
        }

        List<Integer> tempLifeScheduleList = StringUtils.stringToIntegerList(GameConfig.MUSIC_ROOM_SCHEDULE_LIFE, ";");

        Map<Integer, MusicRoomBuildBaseConfig> tempBuildBaseConfigMap = new HashMap<>();
        for (String s : GameConfig.MUSIC_ROOM_BUILD_BASE_ATTRIBUTE.split("\\|")) {
            String[] s1 = s.split("=");
            int buildType = Integer.parseInt(s1[0]);
            List<Integer> params = StringUtils.stringToIntegerList(s1[1], ";");
            MusicRoomBuildBaseConfig buildBaseConfig = new MusicRoomBuildBaseConfig(buildType);
            buildBaseConfig.setParams(params);
            tempBuildBaseConfigMap.put(buildType, buildBaseConfig);
        }

        Set<Integer> tempExpBookFurnitureIdSet = StringUtils.stringToSet(GameConfig.MUSIC_ROOM_BUILD_FURN_ID_EXPBOOK, "\\|");
        Set<Integer> tempSupportsFurnitureIdSet = StringUtils.stringToSet(GameConfig.MUSIC_ROOM_BUILD_FURN_ID_SUPPORTITEMS, "\\|");

        Map<Integer, Set<Integer>> tempBadgeUnlockBuildingsMap = parseBadgeUnlockBuildings();

        Set<Integer> tempInitFurnitureSet = StringUtils.stringToSet(GameConfig.MUSIC_ROOM_BUILD_FURN_ID_INIT_UNLOCK, "\\|");

        Map<Integer, Property> tempBuildingUnlockCostMap = parseBuildingUnlockCostMap();

        List<Integer> tempAppraiseNumList = StringUtils.stringToIntegerList(GameConfig.MUSIC_ROOM_GOOD_REVIEWS_RULE_1, ";");

        List<List<Integer>> tempAppraiseAdditionList = new ArrayList<>();
        for (String s : GameConfig.MUSIC_ROOM_GOOD_REVIEWS_ADD.split("\\|")) {
            List<Integer> list = StringUtils.stringToIntegerList(s, ";");
            tempAppraiseAdditionList.add(list);
        }

        furnitureLevelConfigMap = tempFurnitureConfigMap;
        beautyInitAttrConfigMap = tempBeautyInitAttrConfigMap;
        beautyAttrLvUpMultiList = tempBeautyAttrUpMultiList;
        beautyAttrQualityMultiList = tempBeautyAttrQualityMultiList;
        scheduleList = tempScheduleList;
        lifeScheduleList = tempLifeScheduleList;
        buildBaseConfigMap = tempBuildBaseConfigMap;
        missionConfigMap = tempMissionConfigMap;
        expBookFurnitureKindSet = tempExpBookFurnitureIdSet;
        supportsFurnitureKindSet = tempSupportsFurnitureIdSet;
        badgeUnlockBuildingsMap = tempBadgeUnlockBuildingsMap;
        initFurnitureSet = tempInitFurnitureSet;
        buildingUnlockCostMap = tempBuildingUnlockCostMap;
        appraiseNumList = tempAppraiseNumList;
        appraiseAdditionList = tempAppraiseAdditionList;

        int tempFirstStageId = 0;
        for (MusicRoomMissionConfig missionConfig : missionConfigMap.values()) {
            if (tempFirstStageId == 0) {
                tempFirstStageId = missionConfig.getId();
            }
            if (missionConfig.getId() < tempFirstStageId) {
                tempFirstStageId = missionConfig.getId();
            }
        }
        firstStageId = tempFirstStageId;


        nextTimeNumberTime = 0;
        nextRewardTime = 0;
    }

    public static Map<Integer, Set<Integer>> parseBadgeUnlockBuildings() {
        Map<Integer, Set<Integer>> tempBadgeUnlockBuildingsMap = new HashMap<>();
        Map<Integer, BadgeConfig> badgeConfigMap = BadgeConfigMgr.getBadgeConfigMap(eBadgeType.MusicRoom.getValue());
        for (BadgeConfig badgeConfig : badgeConfigMap.values()) {
            List<Integer> unlockBuildings = new ArrayList<>();
            if (!badgeConfig.getExParam().equals("0")) {
                unlockBuildings = StringUtils.stringToIntegerList(badgeConfig.getExParam(), "\\|");
            }
            tempBadgeUnlockBuildingsMap.put(badgeConfig.getLevel(), new HashSet<>(unlockBuildings));
        }

        for (Integer level : tempBadgeUnlockBuildingsMap.keySet()) {
            for (Integer i = 1; i < level; i++) {
                Set<Integer> unlockIds = tempBadgeUnlockBuildingsMap.get(i);
                if (unlockIds == null) {
                    continue;
                }
                tempBadgeUnlockBuildingsMap.get(level).addAll(unlockIds);
            }
        }

        return tempBadgeUnlockBuildingsMap;
    }

    public static Map<Integer, MusicRoomBeautyInitAttrConfig> parseBeautyInitAttrConfig(int occupation, String str) {
        Map<Integer, MusicRoomBeautyInitAttrConfig> tempMap = new HashMap<>();
        String[] s1 = str.split("\\|");
        for (String s : s1) {
            String[] s2 = s.split("=");
            int number = Integer.parseInt(s2[0]);
            List<Integer> attrList = StringUtils.stringToIntegerList(s2[1], ";");
            MusicRoomBeautyInitAttrConfig attrConfig = new MusicRoomBeautyInitAttrConfig(occupation, number);
            attrConfig.setAttrList(attrList);
            tempMap.put(number, attrConfig);
        }
        return tempMap;
    }

    public static Map<Integer, Property> parseBuildingUnlockCostMap() {
        Map<Integer, Property> tempMap = new HashMap<>();
        for (String s : GameConfig.MUSIC_ROOM_BUILD_UNLOCK_COST.split("\\|")) {
            String[] split = s.split(";");
            int buildId = Integer.parseInt(split[0]);
            Property cost = PropertyHelper.parseStringToProperty(split[1]);
            tempMap.put(buildId, cost);
        }
        return tempMap;
    }

    public void addManagerReloadListener() {
        ConfigMgr.addReloadListener(() -> {
            reloadMusicRoomConfig();
        });
    }

    /**
     * 计算当前时辰
     *
     * @return
     */
    public static void calcNowTimeNumber() {
        long currentTime = DateHelper.getCurrentTime();
        //今天走过的秒数
        if (nextTimeNumberTime == 0 || currentTime >= nextTimeNumberTime) {
            int todaySecond = DateHelper.getTodaySecond();// 今天经过的秒
            int timeAmount = (todaySecond + 1) / GameConfig.MUSIC_ROOM_HOUR_REALITY_TIME;
            int timeNumber = timeAmount % GameConfig.MUSIC_ROOM_ALL_TIME_NUMBER + 1;
            nowTimeNumber = timeNumber;
            nextTimeNumberTime = BigInteger.valueOf(timeAmount + 1)
                    .multiply(BigInteger.valueOf(GameConfig.MUSIC_ROOM_HOUR_REALITY_TIME))
                    .multiply(BigInteger.valueOf(DateHelper.SECOND_MILLIONS))
                    .add(BigInteger.valueOf(DateHelper.getTodayZeroTimeStamp())).longValue();
        }

        if (nextRewardTime == 0 || currentTime >= nextRewardTime) {
            int todaySecond = DateHelper.getTodaySecond();// 今天经过的秒
            int timeAmount = (todaySecond + 1) / GameConfig.MUSIC_ROOM_OUTPUT_TIME;
            nextRewardTime = BigInteger.valueOf(timeAmount + 1)
                    .multiply(BigInteger.valueOf(GameConfig.MUSIC_ROOM_OUTPUT_TIME))
                    .multiply(BigInteger.valueOf(DateHelper.SECOND_MILLIONS))
                    .add(BigInteger.valueOf(DateHelper.getTodayZeroTimeStamp())).longValue();
        }
    }

    /**
     * 当前时辰
     *
     * @return
     */
    public static int getNowTimeNumber() {
        calcNowTimeNumber();
        return nowTimeNumber;
    }

    /**
     * 下一个时辰的起始时间
     *
     * @return
     */
    public static long getNextTimeNumberTime() {
        calcNowTimeNumber();
        return nextTimeNumberTime;
    }

    public static int getTimeNumberByTime(long lastCheckTime) {
        long zeroTimeStamp = DateHelper.getZeroTimeStamp(lastCheckTime);
        long passSeconds = (lastCheckTime - zeroTimeStamp) / DateHelper.SECOND_MILLIONS; //所在天经过的秒数
        int timeAmount = (int) (passSeconds / GameConfig.MUSIC_ROOM_HOUR_REALITY_TIME);
        int timeNumber = timeAmount % GameConfig.MUSIC_ROOM_ALL_TIME_NUMBER + 1;
        return timeNumber;
    }

    public static long getNextRewardTime() {
        calcNowTimeNumber();
        return nextRewardTime;
    }

    public static long getNowRewardTime() {
        calcNowTimeNumber();
        return nextRewardTime - GameConfig.MUSIC_ROOM_OUTPUT_TIME * DateHelper.SECOND_MILLIONS;
    }

    /**
     * 当前时辰的起始时间
     *
     * @return
     */
    public static long getNowTimeNumberStartTime() {
        long startTime = getNextTimeNumberTime() - GameConfig.MUSIC_ROOM_HOUR_REALITY_TIME * DateHelper.SECOND_MILLIONS;
        return startTime;
    }

    public static boolean canUnlockBuilding(int badgeLevel, int buildId) {
        Set<Integer> unlockBuildings = badgeUnlockBuildingsMap.get(badgeLevel);
        if (unlockBuildings == null) {
            return false;
        }
        return unlockBuildings.contains(buildId);
    }

    public static List<Integer> getUnlockBuildingList(int badgeLevel) {
        Set<Integer> unlockBuildings = badgeUnlockBuildingsMap.get(badgeLevel);
        if (unlockBuildings == null) {
            return new ArrayList<>();
        }
        return new ArrayList<>(unlockBuildings);
    }

    public static int getBuildType(int buildId) {
        return buildId / 100;
    }

    public static int getScheduleType(int buildId) {
        MusicRoomBuildBaseConfig buildBaseConfig = getBuildBaseConfig(buildId);
        if (buildBaseConfig == null) {
            return 0;
        }
        return buildBaseConfig.getScheduleType();
    }

    public static MusicRoomBuildBaseConfig getBuildBaseConfig(int buildId) {
        int buildTypeId = getBuildType(buildId);
        return buildBaseConfigMap.get(buildTypeId);
    }

    public static MusicRoomFurnitureConfig getFurnitureConfig(int level) {
        return furnitureLevelConfigMap.get(level);
    }

    public static int getFurnitureMaxLevel() {
        return furnitureLevelConfigMap.size();
    }

    public static int getFirstStageId() {
        return firstStageId;
    }

    public static MusicRoomMissionConfig getStageConfig(int stageId) {
        return missionConfigMap.get(stageId);
    }

    public static MusicRoomBeautyInitAttrConfig getBeautyInitAttrConfig(int occupation, int number) {
        Map<Integer, MusicRoomBeautyInitAttrConfig> map = beautyInitAttrConfigMap.get((short)occupation);
        if (map == null) {
            return null;
        }
        return map.get(number);
    }

    /**
     * 根据属性类型获得等级成长系数
     * 妙音坊--美女属性 ，升级倍数千分比（舞蹈；创作；仪态；乐器；声乐；舒适度；心情值；饱食度）
     * @param index
     * @return
     */
    public static int getBeautyAttrLvUpMulti(int index) {
        if (index < 0 || index >= beautyAttrLvUpMultiList.size()) {
            return 0;
        }
        return beautyAttrLvUpMultiList.get(index);
    }

    /**
     * 根据品质获得属性成长系数
     * 妙音坊--美女属性 ，品质倍数千分比（普通|优秀|卓越|传奇|无双）
     * @param index
     * @return
     */
    public static int getBeautyAttrQualityMulti(int index) {
        if (index < 0 || index >= beautyAttrQualityMultiList.size()) {
            return 1000;
        }
        return beautyAttrQualityMultiList.get(index);
    }

    /**
     * 属性成长值计算
     * 初始值×[ ( 美女局内等级 - 1 ) × 千分比 + 1 ] × 品质倍数
     *
     * @param beautyData
     * @param beautyInfo
     * @param quality
     * @return
     */
    public static UserMusicRoomBeautyData calcAndSetBeautyAttr(UserMusicRoomBeautyData beautyData, BeautyInfo beautyInfo, int quality) {
        int occupation = beautyInfo.getOccupation();
        MusicRoomBeautyInitAttrConfig initAttrConfig = getBeautyInitAttrConfig(occupation, beautyInfo.getMusicRoomInitType());
        if (initAttrConfig == null) {
            getLogger().error("找不到美人初始属性配置, occupation={}, initType={}", occupation, beautyInfo.getMusicRoomInitType());
            return beautyData;
        }

        for (int i = 0; i < initAttrConfig.getAttrList().size(); i++) {
            int attrInitValue = initAttrConfig.getAttrList().get(i);
            int lvUpMulti = getBeautyAttrLvUpMulti(i); // 等级成长系数 千分比
            int qualityMulti = getBeautyAttrQualityMulti(quality - 1); // 品质成长系数 千分比

            long newAttrValue = BigDecimal.valueOf(attrInitValue)
                    .multiply((BigDecimal.valueOf(beautyData.getLevel() - 1).multiply(BigDecimal.valueOf(lvUpMulti)).divide(BigDecimal.valueOf(1000)).add(BigDecimal.ONE)))
                    .multiply(BigDecimal.valueOf(qualityMulti).divide(BigDecimal.valueOf(1000))).setScale(0, BigDecimal.ROUND_UP)
                    .longValue();

            beautyData.setAttr(i, newAttrValue);
        }

        return beautyData;

    }

    public static boolean checkBuildingTypeRight(int buildId, eMusicRoomBuildingType type) {
        MusicRoomBuildBaseConfig buildBaseConfig = getBuildBaseConfig(buildId);
        if (buildBaseConfig == null) {
            return false;
        }
        return buildBaseConfig.getBuildType() == type.getValue();
    }

    public static List<Integer> getLifeScheduleList() {
        return new ArrayList<>(lifeScheduleList);
    }

    public static List<Integer> randomStudyWorkScheduleList() {
        int size = scheduleList.size();
        int index = randomHelper.next(size);
        return new ArrayList<>(scheduleList.get(index));
    }

    public static int randomStudyWorkScheduleListIndex() {
        int size = scheduleList.size();
        return randomHelper.next(size);
    }

    public static List<Integer> getStudyWorkScheduleList(int index) {
        if (index < 0 || index >= scheduleList.size()) {
            return new ArrayList<>();
        }
        return new ArrayList<>(scheduleList.get(index));
    }

    /**
     * 家具种类id = 家具建筑类型ID×10000+家具种类ID×100
     *
     * @param buildType
     * @param furnitureId
     * @return
     */
    public static int getFurnitureKindId(int buildType, int furnitureId) {
        return buildType * 10000 + furnitureId * 100;
    }

    public static int getFurnitureIdByKindId(int furnitureKindId) {
        return (furnitureKindId % 10000) / 100;
    }

    public static int getFurnitureUniqueId(int buildId, int furnitureId) {
        return buildId * 10000 + furnitureId;
    }

    public static int getBuildIdByFurnitureUniqueId(int furnitureUniqueId) {
        return furnitureUniqueId / 10000;
    }

    public static int getFurnitureIdByFurnitureUniqueId(int furnitureUniqueId) {
        return furnitureUniqueId % 10000;
    }

    /**
     * 获得建筑的家具产出经验书
     *
     * @return
     */
    public List<List<Property>> getFurnitureExpBooksProduce(UserMusicRoomBuildingData buildingData) {
        List<List<Property>> expBooksList = new ArrayList<>();
        int buildType = MusicRoomConfigMgr.getBuildType(buildingData.getBuildId());
        for (MusicRoomFurnitureInfo furnitureInfo : buildingData.getFurnitureInfos()) {
            int furnitureKindId = getFurnitureKindId(buildType, furnitureInfo.getId());
            if (!expBookFurnitureKindSet.contains(furnitureKindId)) {
                continue;
            }
            MusicRoomFurnitureConfig furnitureConfig = getFurnitureConfig(furnitureInfo.getLevel());
            expBooksList.addAll(furnitureConfig.getProduceExpBooksList(buildType));
        }

        return expBooksList;
    }

    public static boolean isFurnitureProduceExpBook(int buildType, int furnitureId) {
        int furnitureKindId = getFurnitureKindId(buildType, furnitureId);
        return expBookFurnitureKindSet.contains(furnitureKindId);
    }

    public static boolean isFurnitureProduceSupportItem(int buildType, int furnitureId) {
        int furnitureKindId = getFurnitureKindId(buildType, furnitureId);
        return supportsFurnitureKindSet.contains(furnitureKindId);
    }

    /**
     * 获得建筑的家具产出应援物
     */
    public List<List<Property>> getFurnitureSupportItemsProduce(UserMusicRoomBuildingData buildingData) {
        List<List<Property>> supportItemsList = new ArrayList<>();
        int buildType = MusicRoomConfigMgr.getBuildType(buildingData.getBuildId());
        for (MusicRoomFurnitureInfo furnitureInfo : buildingData.getFurnitureInfos()) {
            int furnitureKindId = getFurnitureKindId(buildType, furnitureInfo.getId());
            if (!supportsFurnitureKindSet.contains(furnitureKindId)) {
                continue;
            }
            MusicRoomFurnitureConfig furnitureConfig = getFurnitureConfig(furnitureInfo.getLevel());
            supportItemsList.addAll(furnitureConfig.getProduceSupportItemsList(buildType));
        }

        return supportItemsList;
    }


    /**
     * 获得美女的妙音坊美名技能升级消耗道具id
     * @param occupation
     * @return
     */
    public static int getBeautySkillLvUpCostId(int occupation) {
        Map<Integer, GoodsInfo> infoMap = GoodsMgr.getGoodsMapByType(eGoodsType.MusicRoomBeautySkillExp.getValue());
        if (infoMap == null) {
            return 0;
        }
        for (GoodsInfo goodsInfo : infoMap.values()) {
            if (goodsInfo.getParamList().get(0).intValue() == occupation) {
                return goodsInfo.getGoodsId();
            }
        }

        return 0;
    }

    /**
     * 根据行程类型，找到对应的建筑,保底都有宿舍,返回null,表示返回入住的宿舍
     */
    public static UserMusicRoomBuildingData searchBuildingByScheduleType(List<UserMusicRoomBuildingData> buildingDataList, int scheduleType, boolean isNext) {
        if (scheduleType == eMusicRoomScheduleType.Rest.getValue()) {//休息行程回到自己入住的那个宿舍
            return null;
        }

        UserMusicRoomBuildingData resultBuildingData = null;
        for (UserMusicRoomBuildingData buildingData : buildingDataList) {
            MusicRoomBuildBaseConfig buildBaseConfig = MusicRoomConfigMgr.getBuildBaseConfig(buildingData.getBuildId());
            if (!isNext) {
                int beautyNum = buildingData.getNowCheckInBeautyIds().size(); //建筑里的美女数
                if (beautyNum >= buildBaseConfig.getCheckInNumLimit()) {//人满了找下一个
                    continue;
                }
            } else {
                int beautyNum = buildingData.getWaitCheckInBeautyIds().size();
                if (beautyNum >= buildBaseConfig.getCheckInNumLimit()) {//人满了找下一个
                    continue;
                }
            }

            resultBuildingData = buildingData;
            break;
        }
        return resultBuildingData;
    }

    public static MusicRoomRoutingBuilding searchBuildingByScheduleTypeEx(List<MusicRoomRoutingBuilding> buildingDataList, int scheduleType, boolean isNext) {
        if (scheduleType == eMusicRoomScheduleType.Rest.getValue()) {//休息行程回到自己入住的那个宿舍
            return null;
        }

        MusicRoomRoutingBuilding resultBuildingData = null;
        for (MusicRoomRoutingBuilding buildingData : buildingDataList) {
            MusicRoomBuildBaseConfig buildBaseConfig = MusicRoomConfigMgr.getBuildBaseConfig(buildingData.getBuildId());
            if (!isNext) {
                int beautyNum = buildingData.getNowCheckInBeautyIds().size(); //建筑里的美女数
                if (beautyNum >= buildBaseConfig.getCheckInNumLimit()) {//人满了找下一个
                    continue;
                }
            } else {
                int beautyNum = buildingData.getWaitCheckInBeautyIds().size();
                if (beautyNum >= buildBaseConfig.getCheckInNumLimit()) {//人满了找下一个
                    continue;
                }
            }

            resultBuildingData = buildingData;
            break;
        }
        return resultBuildingData;
    }

    /**
     * 计算美女经过指定时辰后的结果
     *
     * @param tempBeautyDataList   有行程的美女,排序好了的
     * @param tempBuildingDataMap  解锁的所有建筑
     * @param passTimerAmount      经过多少时辰
     * @param checkStartTimeNumber 开始的时辰
     */
    public static MusicRoomRoutingResult calcBeautyRouting(List<UserMusicRoomBeautyData> tempBeautyDataList, Map<Integer, UserMusicRoomBuildingData> tempBuildingDataMap,
                                                           int passTimerAmount, int checkStartTimeNumber) {

        List<MusicRoomRoutingBeauty> beautyDataList = new ArrayList<>();
        for (UserMusicRoomBeautyData beautyData : tempBeautyDataList) {
            MusicRoomRoutingBeauty routingBeauty = new MusicRoomRoutingBeauty(beautyData);
            beautyDataList.add(routingBeauty);
        }

        Map<Integer, MusicRoomRoutingBuilding> buildingDataMap = new HashMap<>();//缓存的建筑信息
//        Map<Integer, MusicRoomScheduleAttrChange> scheduleAttrChangeMap = new HashMap<>();//统计的行程属性变化

        Map<Integer, List<MusicRoomRoutingBuilding>> tempBuildingListMap = new HashMap<>();
        for (UserMusicRoomBuildingData buildingData : tempBuildingDataMap.values()) {
            int scheduleType = MusicRoomConfigMgr.getScheduleType(buildingData.getBuildId());
            MusicRoomRoutingBuilding routingBuilding = new MusicRoomRoutingBuilding(buildingData, scheduleType);
            buildingDataMap.put(routingBuilding.getBuildId(), routingBuilding);
            List<MusicRoomRoutingBuilding> list = tempBuildingListMap.get(scheduleType);
            if (list == null) {
                list = new ArrayList<>();
                tempBuildingListMap.put(scheduleType, list);
            }
            list.add(routingBuilding);

//            MusicRoomScheduleAttrChange scheduleAttrChange = scheduleAttrChangeMap.get(scheduleType);
//            if (scheduleAttrChange == null) {
//                scheduleAttrChange = new MusicRoomScheduleAttrChange();
//                scheduleAttrChangeMap.put(scheduleType, scheduleAttrChange);
//            }
//            scheduleAttrChange.setComfortAdd(scheduleAttrChange.getComfortAdd() + buildingData.getComfortAdd());
//            scheduleAttrChange.setMoodAdd(scheduleAttrChange.getMoodAdd() + buildingData.getMoodAdd());
//            scheduleAttrChange.setSatietyAdd(scheduleAttrChange.getSatietyAdd() + buildingData.getSatietyAdd());
//            scheduleAttrChange.setComfortReduce(scheduleAttrChange.getComfortReduce() + buildingData.getComfortReduce());
//            scheduleAttrChange.setMoodReduce(scheduleAttrChange.getMoodReduce() + buildingData.getMoodReduce());
//            scheduleAttrChange.setSatietyReduce(scheduleAttrChange.getSatietyReduce() + buildingData.getSatietyReduce());
        }

//        //按照建筑的总等级排序
//        for (Map.Entry<Integer, List<MusicRoomRoutingBuilding>> entry : tempBuildingListMap.entrySet()) {
//            List<MusicRoomRoutingBuilding> list = new ArrayList<>(entry.getValue());
//            list.sort((o1, o2) -> {
//                int compare = Integer.compare(o2.getTotalFurnitureLevel(), o1.getTotalFurnitureLevel());
//                if (compare == 0) {
//                    return Integer.compare(o1.getBuildId(), o2.getBuildId());
//                }
//                return compare;
//            });
//            entry.setValue(list);
//        }

        //记录美女经过的建筑
        Map<Integer, List<List<Integer>>> beautyRoutingChangeMap = new HashMap<>();
        //记录美女每轮的路线类型 0是生活 非0是随机的工作行程序号
        Map<Integer, List<Integer>> beautyRoutingTypeMap = new HashMap<>();
        //初始记录
        for (MusicRoomRoutingBeauty beautyData : beautyDataList) {
            List<List<Integer>> listList = beautyRoutingChangeMap.get(beautyData.getBeautyId());
            if (listList == null) {
                listList = new ArrayList<>();
                beautyRoutingChangeMap.put(beautyData.getBeautyId(), listList);
            }
            ArrayList<Integer> list = new ArrayList<>();
            list.add(beautyData.getNowBuildingId());
            listList.add(list);

            List<Integer> typeList = beautyRoutingTypeMap.get(beautyData.getBeautyId());
            if (typeList == null) {
                typeList = new ArrayList<>();
                beautyRoutingTypeMap.put(beautyData.getBeautyId(), typeList);
            }
            typeList.add(beautyData.getScheduleListType());
        }

        for (int i = 0; i < passTimerAmount; i++) {
            int passCheckTimeNumber = (checkStartTimeNumber + 1 + i) % GameConfig.MUSIC_ROOM_ALL_TIME_NUMBER;
            if (passCheckTimeNumber == 0) {
                passCheckTimeNumber = GameConfig.MUSIC_ROOM_ALL_TIME_NUMBER;
            }

            //结算美女当前建筑
            for (MusicRoomRoutingBeauty beautyData : beautyDataList) {
                MusicRoomRoutingBuilding buildingData = buildingDataMap.get(beautyData.getNowBuildingId());
                if (buildingData == null) {
                    continue;
                }

//                if (!(beautyData.getLiveInTime() > beautyData.getLastTimerEndTime() && i == 0)) {
//                    //入住的那个时辰,不计算产出
//                    MusicRoomScheduleAttrChange attrChange = scheduleAttrChangeMap.get(buildingData.getScheduleType());
//                    beautyData.addComfort(attrChange.getComfortAdd());
//                    beautyData.addMood(attrChange.getMoodAdd());
//                    beautyData.addSatiety(attrChange.getSatietyAdd());
//                    beautyData.reduceComfort(attrChange.getComfortReduce());
//                    beautyData.reduceMood(attrChange.getMoodReduce());
//                    beautyData.reduceSatiety(attrChange.getSatietyReduce());
//
//                    Property expBooksReward = PropertyHelper.randomPropertyByListList(buildingData.getProduceExpBookList());
//                    Property supportsReward = PropertyHelper.randomPropertyByListList(buildingData.getProduceSupportItemList());
//
//                    //累计建筑产出
//                    buildingData.addAmountReward(expBooksReward);
//                    buildingData.addAmountReward(supportsReward);
//                    buildingData.addBeautySettleTimes(beautyData.getBeautyId());
//                }

//                if (isForceChangeToLifeRouting) {
//                    //如果总体属性变化趋势少于设定值,切换生活行程
//                    //tips目前是策划要的是当前时辰结束马上切换
//                    if (beautyData.getScheduleListType() > 0) {
//                        beautyData.setScheduleListType(0);
//                        List<Integer> newScheduleList = MusicRoomConfigMgr.getLifeScheduleList();
//                        beautyData.setScheduleList(newScheduleList);
//
//                        //新的一轮行程
//                        List<Integer> typeList = beautyRoutingTypeMap.get(beautyData.getBeautyId());
//                        typeList.add(beautyData.getScheduleListType());
//
//                        List<List<Integer>> listList = beautyRoutingChangeMap.get(beautyData.getBeautyId());
//                        listList.add(new ArrayList<>());
//                    }
//                }

                //美女当前建筑移出该美女
                buildingData.removeNowBeautyId(beautyData.getBeautyId());

                //如果是最后1个时辰了,判断替换行程的条件
                if (passCheckTimeNumber == 1) {
//                    boolean isWorkList = beautyData.getScheduleListType() > 0;
//                    if (!isForceChangeToLifeRouting && beautyData.getScheduleListType() == 0 && !beautyData.isAnyOneAttrLessThenZero()) {
//                        //在生活行程结束时,如果美女的三项属性都>=80%,则更新为工作行程
////                        int listIndex = randomStudyWorkScheduleListIndex();
////                        List<Integer> newScheduleList = getStudyWorkScheduleList(listIndex);
////                        beautyData.setScheduleListType(listIndex + 1);
////                        beautyData.setScheduleList(newScheduleList);
//                        isWorkList = true;
//                    }
//                    if (beautyData.getScheduleListType() > 0 && beautyData.isAnyOneAttrLessThenZero()) {
//                        //在工作行程结束时,如果美女的三项属性有任一项<20%,则更新为生活行程,tips需求变动废弃
//                        //任意一项小于等于0,切换生活行程
//                        beautyData.setScheduleListType(0);
//                        List<Integer> newScheduleList = getLifeScheduleList();
//                        beautyData.setScheduleList(newScheduleList);
//                        isWorkList = false;
//                    }
//                    if (isWorkList){
//                        //工作行程每次结束都随机行程
//                        int listIndex = randomStudyWorkScheduleListIndex();
//                        List<Integer> newScheduleList = getStudyWorkScheduleList(listIndex);
//                        beautyData.setScheduleListType(listIndex + 1);
//                        beautyData.setScheduleList(newScheduleList);
//                    }

                    int listIndex = randomStudyWorkScheduleListIndex();
                    List<Integer> newScheduleList = getStudyWorkScheduleList(listIndex);
                    beautyData.setScheduleListType(listIndex + 1);
                    beautyData.setScheduleList(newScheduleList);

                    //新的一轮行程
                    List<Integer> typeList = beautyRoutingTypeMap.get(beautyData.getBeautyId());
                    typeList.add(beautyData.getScheduleListType());

                    List<List<Integer>> listList = beautyRoutingChangeMap.get(beautyData.getBeautyId());
                    listList.add(new ArrayList<>());
                }
            }

            //美女进入下一个建筑
            for (MusicRoomRoutingBeauty beautyData : beautyDataList) {
                int schedule = beautyData.getSchedule( passCheckTimeNumber);
                MusicRoomRoutingBuilding searchBuildingData = MusicRoomConfigMgr.searchBuildingByScheduleTypeEx(tempBuildingListMap.getOrDefault(schedule, new ArrayList<>()), schedule, false);
                if (searchBuildingData == null) {
                    searchBuildingData = buildingDataMap.get(beautyData.getLiveInBuildId());
                }
                if (searchBuildingData != null) {//入住数据更新
                    searchBuildingData.addNowBeautyId(beautyData.getBeautyId());
                    beautyData.setNowBuildingId(searchBuildingData.getBuildId());
                }

                //记录美女经过的建筑
                List<List<Integer>> listList = beautyRoutingChangeMap.get(beautyData.getBeautyId());
                listList.get(beautyRoutingTypeMap.get(beautyData.getBeautyId()).size() - 1).add(beautyData.getNowBuildingId());
            }
        }

        //更新美女下一个建筑
        for (MusicRoomRoutingBeauty beautyData : beautyDataList) {
            int schedule = beautyData.getSchedule(nowTimeNumber + 1);
            MusicRoomRoutingBuilding searchBuildingData = MusicRoomConfigMgr.searchBuildingByScheduleTypeEx(tempBuildingListMap.getOrDefault(schedule, new ArrayList<>()), schedule, true);
            if (searchBuildingData == null) {
                searchBuildingData = buildingDataMap.get(beautyData.getLiveInBuildId());
            }
            if (searchBuildingData != null) {
                searchBuildingData.addWaitCheckInBeautyId(beautyData.getBeautyId());
                beautyData.setNextBuildingId(searchBuildingData.getBuildId());
            }
        }


        MusicRoomRoutingResult calcResult = new MusicRoomRoutingResult(beautyDataList, buildingDataMap);
        calcResult.setBeautyRoutingMap(beautyRoutingChangeMap);
        calcResult.setBeautyRoutingTypeMap(beautyRoutingTypeMap);

        return calcResult;
    }

    /**
     * 是否初始1级的家具
     *
     * @return
     */
    public static boolean isInitUnlockFurniture(int buildId, int furnitureId) {
        int buildType = getBuildType(buildId);
        int furnitureKindId = getFurnitureKindId(buildType, furnitureId);
        return initFurnitureSet.contains(furnitureKindId);
    }

    public static boolean isNeedChangeScheduleToLife(long totalComfortAdd, long totalMoodAdd, long totalSatietyAdd, long totalComfortReduce, long totalMoodReduce, long totalSatietyReduce) {
        boolean isNeedChange = false;
        long checkPercent = GameConfig.MUSIC_ROOM_ATTRIBUTE_WARN_MULTIPLE;
        if (totalComfortReduce > 0) {
            int comparePercent = BigInteger.valueOf(totalComfortAdd).multiply(BigInteger.valueOf(1000)).divide(BigInteger.valueOf(totalComfortReduce)).intValue();
            if (comparePercent < checkPercent) {
                isNeedChange = true;
            }
        }
        if (totalMoodReduce > 0) {
            int comparePercent = BigInteger.valueOf(totalMoodAdd).multiply(BigInteger.valueOf(1000)).divide(BigInteger.valueOf(totalMoodReduce)).intValue();
            if (comparePercent < checkPercent) {
                isNeedChange = true;
            }
        }
        if (totalSatietyReduce > 0) {
            int comparePercent = BigInteger.valueOf(totalSatietyAdd).multiply(BigInteger.valueOf(1000)).divide(BigInteger.valueOf(totalSatietyReduce)).intValue();
            if (comparePercent < checkPercent) {
                isNeedChange = true;
            }
        }
        return isNeedChange;
    }

    public static Property getBadgePerTimerReward(int badgeLevel, int timerAmount) {
        Property timerProduce = new Property();
        BadgeConfig badgeConfig = BadgeConfigMgr.getBadgeConfigByLevel(eBadgeType.MusicRoom.getValue(), badgeLevel);
        if (badgeConfig == null) {
            return timerProduce;
        }
        timerProduce = PropertyHelper.parseStringToProperty(badgeConfig.getSpecialEffect());
        timerProduce.goodCountMultiNum(timerAmount);
        return timerProduce;
    }

    public static Property getBuildingUnlockCost(int buildId) {
        Property cost = new Property();
        if (buildingUnlockCostMap.containsKey(buildId)) {
            cost = buildingUnlockCostMap.get(buildId);
        }
        return cost;
    }

    /**
     * 根据繁荣度获得配置
     *
     * @param prosperity
     * @return
     */
    public static MusicRoomFurnitureConfig getFurnitureConfigByProsperity(long prosperity) {
        MusicRoomFurnitureConfig takeConfig = null;
        for (int i = 1; i <= 1000; i++) {
            MusicRoomFurnitureConfig furnitureConfig = MusicRoomConfigMgr.getFurnitureConfig(i);
            if (furnitureConfig == null) {
                break;
            }
            if (i > 1 && furnitureConfig.getNeedProsperity() == 0) {
                break;
            }
            if (prosperity >= furnitureConfig.getNeedProsperity()) {
                takeConfig = furnitureConfig;
            } else {
                break;
            }
        }

        return takeConfig;
    }

    public static int getBadAppraiseNum() {
        if (appraiseNumList.size() < 1) {
            return 0;
        }
        return appraiseNumList.get(0);
    }

    public static int getGoodAppraiseNum() {
        if (appraiseNumList.size() < 2) {
            return 0;
        }
        return appraiseNumList.get(1);
    }

    public static int getAllAppraiseNum() {
        int totalNum = 0;
        for (Integer num : appraiseNumList) {
            totalNum += num;
        }
        return totalNum;
    }

    /**
     * 获取好评加成
     */
    public static int getGoodAppraiseAddition(int goodNum, int totalNum) {
        if (totalNum == 0) {
            return 0;
        }
        int result = 0;
        int compareValue = BigDecimal.valueOf(goodNum).divide(BigDecimal.valueOf(totalNum), 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(1000)).intValue();
        for (List<Integer> list : appraiseAdditionList) {
            Integer checkValue = list.get(0);
            Integer addition = list.get(1);
            if (compareValue >= checkValue) {
                result = addition;
            } else {
                break;
            }
        }
        return result;
    }
}

